const app = getApp();
// const http = require("./../../../utils/http.js");

// let genderArray = ['男', '女', '人妖', '未知生物'];

Page({
    data: {
        InputBottom: 0,
        startFooterLoading: false,//加载状态
        sale: null,
        comments: '', // roleCodes: wx.getStorageSync('ALLINFO').bbsUserRecord.roleCodeList,
        // roleCodes: [],
        UPLOAD_IMAGE: app.globalData.UPLOAD_IMAGE,
        showCommentInput: false,
        inputShowed: false,
        username: false,
        isAdmin: false,
        content: '',
        objId: '',
        objType: '',
        // refCommentId: '',
        pid: '0',
        beReplyUsername: '',
        beReplyRealname: '',
        replydetail: {},


        attachments: '',
        canFollow: true,
        param: app.globalData.param,

        pageNo: 1,
        pageSize: 10,
        replyList: [],

        actionCommentGroups: {},
        showCommentActionsheet: false,

    },
    onLoad: function (option) {
        // console.log(this)
        // console.log('管理员', this.data.isAdmin)
        // console.log(option);
        //
        // console.log(app.globalData.param)

        let objId = option.id;
        this.setData({
            objId: objId,
            username: wx.getStorageSync('ALLINFO').sysUser.username,
            isAdmin: wx.getStorageSync('ALLINFO').bbsUserRecord.roleCodeList.includes('superadmin'),

            param: app.globalData.param
        })
        app.wxRequest('get', app.globalData.HOSTURL + "/bbs/bbsSaleFriends/wise/mini/fullById?id=" + objId, null).then(res => {
            console.log(res);
            let data = res.data.result;
            //如果userIsDelete为false，判断当前用户角色是否为管理员权限，如果有，将userIsDelete设置为true
            // if (data.userIsDelete == false) {
            //     if (this.data.roleCodes.includes("superadmin")) {
            //         data.userIsDelete = true;
            //     }
            // }
            this.setData({
                sale: data,
            });

        });
        //    获取评论列表

        this.getCommentList()
        // let param = {
        //     'topicId': objId,
        // }
        // app.wxRequest('post', app.globalData.HOSTURL + "/bbs/bbsSaleFriendsReply/wise/mini/rootFullList?pageNo=1&pageSize=10", param).then(res => {
        //     console.log('评论列表', res)
        //     this.setData({
        //         replyList: res.data.result.records
        //     })
        // })
    },
    goUserInfo(e) {
        console.log(e)
        wx.navigateTo({
            url: '/pages/components/mine/userinfo/userinfo?username=' + e.currentTarget.dataset.username,
        })
    },
    getCommentList(isNew = false) {
        const that = this
        let pageNo
        if (isNew) {
            pageNo = 1
        } else {
            pageNo = that.data.pageNo
        }

        //    获取评论列表
        that.setData({
            startFooterLoading: true
        })
        let param = {
            'topicId': this.data.objId,
        }
        app.wxRequest('post', app.globalData.HOSTURL + `/bbs/bbsSaleFriendsReply/wise/mini/rootFullList?pageNo=${pageNo}&pageSize=${that.data.pageSize}`, param).then(res => {
            console.log('评论列表', res)
            wx.hideLoading();
            let replyTemp = []

            if (res.data.result.records.length > 0) {

                if (isNew) {
                    replyTemp = res.data.result.records
                } else {

                    replyTemp = [...that.data.replyList, ...res.data.result.records]
                }

                console.log(replyTemp)

                that.setData({
                    replyList: replyTemp,
                    pageNo: that.data.pageNo + 1,
                    startFooterLoading: false

                })
            } else {
                //    停止加载
                if (pageNo == 1) {
                    that.setData({
                        replyList: [],

                    })
                }
                that.setData({
                    startFooterLoading: false,

                })
            }


        })
    },


    //评论点赞
    clickReplyPraise(e) {

        console.log(e)
        const id = e.currentTarget.id
        const type = e.currentTarget.dataset.type
        let replyTemp = this.data.replyList
        const accountState = app.globalData.accountState
        if (app.globalData.HASUSERINFO) {
            if (accountState.isDisable && accountState.state == accountState.BLOCKING) {
                wx.showToast({
                    title: `您的账号已被${accountState.stateName},剩余时间${accountState.disableDay}`,
                    icon: 'none'
                })
            } else {
                console.log(id)
                if (type == '1') {
                    //    单父
                    let index = this.data.replyList.findIndex(item => item.id == id)
                    console.log(index)
                    app.wxRequest('get', app.globalData.HOSTURL + `/bbs/bbsSaleFriendsReplyPraise/wise/mini/praise?id=${id}`, {}).then(res => {
                        console.log(res)
                        if (res.data.result) {
                            //    添加
                            replyTemp[index].userIsPraise = true
                            if (replyTemp[index].praise != null) {
                                replyTemp[index].praise = replyTemp[index].praise + 1
                            } else {
                                replyTemp[index].praise = 1
                            }

                            console.log(replyTemp)
                            this.setData({
                                replyList: replyTemp
                            })
                        } else {
                            //    删除
                            replyTemp[index].userIsPraise = false
                            if (replyTemp[index].praise != null) {
                                replyTemp[index].praise = replyTemp[index].praise - 1
                            } else {
                                replyTemp[index].praise = 0
                            }

                            console.log(replyTemp)
                            this.setData({
                                replyList: replyTemp
                            })
                        }
                    })

                } else {
                    //    子节点
                    let pid = e.currentTarget.dataset.pid
                    let pidIndex = this.data.replyList.findIndex(item => item.id == pid)
                    console.log(pidIndex)
                    let index = this.data.replyList[pidIndex].childFullReply.findIndex(item => item.id == id)
                    app.wxRequest('get', app.globalData.HOSTURL + `/bbs/bbsSaleFriendsReplyPraise/wise/mini/praise?id=${id}`, {}).then(res => {
                        console.log(res)
                        if (res.data.result) {
                            //    添加
                            replyTemp[pidIndex].childFullReply[index].userIsPraise = true
                            if (replyTemp[pidIndex].childFullReply[index].praise != null) {
                                replyTemp[pidIndex].childFullReply[index].praise = replyTemp[pidIndex].childFullReply[index].praise + 1
                            } else {
                                replyTemp[pidIndex].childFullReply[index].praise = 1
                            }

                            console.log(replyTemp)
                            this.setData({
                                replyList: replyTemp
                            })
                        } else {
                            //    删除
                            replyTemp[pidIndex].childFullReply[index].userIsPraise = false
                            if (replyTemp[pidIndex].childFullReply[index].praise != null) {
                                replyTemp[pidIndex].childFullReply[index].praise = replyTemp[pidIndex].childFullReply[index].praise - 1
                            } else {
                                replyTemp[pidIndex].childFullReply[index].praise = 0
                            }

                            console.log(replyTemp)
                            this.setData({
                                replyList: replyTemp
                            })
                        }
                    })


                }

            }
        } else {
            app.getUserProfile()
        }


    },

    //上拉触底
    onReachBottom() {
        console.log('上拉触底')
        this.getCommentList()
    },

    longpress(e) {
        const that = this
        console.log(e)

        const replydetail = e.currentTarget.dataset.replydetail

        let isDelete = replydetail.createBy == that.data.username || that.data.sale.bbsSaleFriendsPage.createBy == that.data.username
        let istipoff = replydetail.createBy != that.data.username

console.log(replydetail.createBy,that.data.username)

        let actionCommentGroupsTemp = [{
            text: '复制',
            value: 0
        }]

        // 自己不能举报自己发布的评论
        if (istipoff) {
            actionCommentGroupsTemp.push({
                text: '举报',
                value: 1
            })
        }

        // 评论发布者可以删除自己评论    帖子发布者可以删除任意评论
        if (isDelete) {
            actionCommentGroupsTemp.push({
                text: '删除',
                value: 2
            })
        }
        //管理员可以删除
        const userRecord = wx.getStorageSync("ALLINFO").bbsUserRecord

        if (userRecord.roleCodeList.includes('superadmin')) {
            actionCommentGroupsTemp.push({
                text: '删除(管理员)',
                value: 3
            })
        }


        that.setData({
            replydetail: replydetail,
            actionCommentGroups: actionCommentGroupsTemp,
            showCommentActionsheet: true,

        })

    },
    clickCommentAction(e) {
        console.log(e)
        var that = this

        const index = e.detail.value
        console.log(index)
        const replydetail = that.data.replydetail
        console.log(replydetail)
        if (replydetail == undefined || replydetail == null || replydetail == {}) {
            return
        }
        switch (index) {
            //复制
            case 0:
                wx.setClipboardData({
                    data: replydetail.content,
                    success(res) {
                        wx.showToast({
                            title: '复制成功', icon: 'success', duration: 2500,
                        })
                    }
                })
                break
            //举报
            case 1:
                that.tipoffComment(replydetail)
                break
            //删除
            case 2:
                that.deleteComment(replydetail.id)
                break
            //    管理员删除
            case 3:
                that.deleteComment(replydetail.id, true)
                break
        }

        this.setData({
            showCommentActionsheet: false
        })
    },

    tipoffSale() {
        const that = this
        wx.showModal({
            // cancelColor: '#39b54a',
            confirmColor: '#000000',
            title: '举报',
            content: "您确认要举报此帖吗？",
            showCancel: true,
            success(res) {
                if (res.confirm) {
                    var bbsInform = {}
                    bbsInform.saleId = that.data.sale.bbsSaleFriendsPage.id
                    bbsInform.type = 4 //举报卖舍友
                    bbsInform.informUsername = wx.getStorageSync('ALLINFO').sysUser.username
                    bbsInform.beInformUsername = that.data.sale.bbsSaleFriendsPage.createBy

                    let url = `${app.globalData.HOSTURL}/bbs/bbsInform/wise/mini/informSale`
                    app.wxRequest('post', url, bbsInform).then(res => {
                        console.log(res)
                        if (res.data.code == 200) {
                            wx.showToast({
                                title: "举报成功",
                                icon: "success"
                            })
                        } else {
                            wx.showToast({
                                title: res.data.message,
                                icon: "none"
                            })
                        }
                    }, err => {

                    })
                } else if (res.cancel) {
                    // x.showToast({
                    //     title: "取消",
                    //     icon: "none"
                    // })  w
                }
            }
        })
    },

    /**
     * 举报评论
     */
    tipoffComment(replyDetail) {
        var that = this
        wx.showModal({
            // cancelColor: '#39b54a',
            confirmColor: '#000000',
            title: '举报',
            content: "您确认要举报这条评论吗？",
            showCancel: true,
            success(res) {
                if (res.confirm) {
                    var bbsInform = {}
                    bbsInform.saleId = that.data.sale.bbsSaleFriendsPage.id
                    bbsInform.saleReplyId = replyDetail.id
                    bbsInform.type = 5 //举报卖舍友
                    bbsInform.informUsername = wx.getStorageSync('ALLINFO').sysUser.username
                    bbsInform.beInformUsername = replyDetail.createBy

                    let url = `${app.globalData.HOSTURL}/bbs/bbsInform/wise/mini/informSaleReply`
                    app.wxRequest('post', url, bbsInform).then(res => {
                        console.log(res)
                        if (res.data.code == 200) {
                            wx.showToast({
                                title: "举报成功",
                                icon: "success"
                            })
                        } else {
                            wx.showToast({
                                title: res.data.message,
                                icon: "none"
                            })
                        }
                    }, err => {

                    })
                } else if (res.cancel) {
                    // x.showToast({
                    //     title: "取消",
                    //     icon: "none"
                    // })  w
                }
            }
        })
    },

    /**
     * 删除帖子
     */
    deleteSale: function (e) {
        let id = this.data.sale.bbsSaleFriendsPage.id;
        console.log(id);
        const isadmin = e.currentTarget.dataset.isadmin
        wx.showModal({
            title: '提示', content: '确认删除?', success: function (res) {
                if (res.confirm) {
                    //TODO 是否管理员删除

                    app.wxRequest('DELETE', app.globalData.HOSTURL + `/bbs/bbsSaleFriends/mini/delete?id=${id}&isadmin=${isadmin}`, {
                        // id: id
                    }).then(res => {
                        if (res.statusCode == 200) {

                            app.globalData.needReloadSaleFriend = true; // 需要重新加载
                            wx.showToast({
                                title: '删除成功', icon: 'success', duration: 1000,
                            })

                            wx.navigateBack({
                                comeBack: true
                            });
                        }

                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })

    },

    /**
     * 跳转到私信
     */
    letter: function (e) {
        // let id = e.target.dataset.obj;
        // wx.navigateTo({
        //     url: '/pages/personal/letter/letter?friend_id=' + id + '&can_chat=' + true
        // })
    },

    /**
     * 喜欢
     */
    follow: function (e) {
        if (this.data.canFollow == false) {
            return false;
        }

        this.setData({
            canFollow: false
        })
        const accountState = app.globalData.accountState
        if (app.globalData.HASUSERINFO) {
            if (accountState.isDisable && accountState.state == accountState.BLOCKING) {
                wx.showToast({
                    title: `您的账号已被${accountState.stateName},剩余时间${accountState.disableDay}`,
                    icon: 'none'
                })
            } else {

                let objId = this.data.sale.bbsSaleFriendsPage.id;
                console.log(objId);
                app.wxRequest('post', app.globalData.HOSTURL + "/bbs/bbsSaleFriendsStar/wise/mini/starByid", {
                    topicId: objId
                }).then(res => {
                    console.log(res);

                    var body = res.data.result;
                    let that = this;

                    let sale = that.data.sale;
                    sale.userIsStar = body.userIsStar;
                    sale.bbsSaleFriendsPage.praiseCount = body.bbsSaleFriendsPage.praiseCount;
                    this.setData({
                        sale: sale, canFollow: true
                    });

                })
            }
        } else {
            app.getUserProfile()
        }

    },

    /**
     * 取消喜欢
     */
    // cancelFollow: function (e) {
    //     if (this.data.canFollow == false) {
    //         return false;
    //     }
    //
    //     this.setData({
    //         canFollow: false
    //     })
    //
    //     let objId = this.data.sale.id;
    //     http.put(`/cancel/${objId}/follow/2`, {}, res => {
    //         let sale = this.data.sale;
    //         sale.follow = true;
    //         sale.follow_number -= 1
    //         this.setData({
    //             sale: sale, canFollow: true
    //         });
    //     })
    // },

    /**
     * 预览图片
     */
    previewImage: function (event) {
        console.log(event);
        var imageList = []
        for (var itemImage in event.currentTarget.dataset.imagelist) {
            imageList.push(this.data.UPLOAD_IMAGE + event.currentTarget.dataset.imagelist[itemImage].imageUrl);
        }
        let currentImageUrl = this.data.UPLOAD_IMAGE + event.currentTarget.dataset.imagelistitem.imageUrl;
        // console.log(imageList, currentImageUrl)
        wx.previewImage({
            urls: imageList, //需要预览的图片http链接列表，注意是数组
            current: currentImageUrl, // 当前显示图片的http链接，默认是第一个
            success: function (res) {
                console.log("预览成功")
            }, fail: function (res) {
                wx.showToast({
                    title: '图片加载失败', icon: 'none'
                })
                console.log("预览失败")
            }, complete: function (res) {
            },
        })
    },

    /**
     * 触摸屏幕后移动触发一些隐藏操作
     */
    hiddenComment: function () {
        this.setData({
            showCommentInput: false,
            inputShowed: false
        });
    },
    //mark: 评论框获得焦点
    InputFocus(e) {
        console.log("获得焦点", e)
        this.setData({
            InputBottom: e.detail.height,
        })
    },
    // mark:评论框失去焦点
    InputBlur(e) {
        console.log("失去焦点")
        var that = this;


        that.setData({
            InputBottom: 0
        })

    },
    /**
     * 显示评论输入框
     */
    showCommentInput: function (e) {
        console.log('显示输入框')
        console.log(e);
        const replydetail = e.currentTarget.dataset.replydetail
        let pid = e.currentTarget.dataset.pid
        let isBeReply = e.currentTarget.dataset.beReplay
        if (pid == '0') {
            this.setData({
                beReplyRealname: this.data.sale.bbsSaleFriendsPage.realname,
                beReplyUsername: this.data.sale.bbsSaleFriendsPage.createBy,

            })
        } else {

            this.setData({
                beReplyRealname: replydetail.realname,
                beReplyUsername: replydetail.createBy,

            })


        }
        // let type = e.currentTarget.dataset.type;
        // let refId = e.currentTarget.dataset.refid;

        //自动获取焦点

        this.setData({
            inputShowed: true,
            showCommentInput: true,
            replydetail: replydetail,

            pid: pid
        });
    }, /**
     * 删除评论
     */
    deleteComment: function (id, isadmin = false) {
        const that = this;

        wx.showModal({
            title: '提示', content: '确认删除该评论?', success: function (res) {
                if (res.confirm) {
                    app.wxRequest('delete', app.globalData.HOSTURL + `/bbs/bbsSaleFriendsReply/wise/mini/delete?id=${id}&isadmin=${isadmin}`,
                        {}).then(res => {
                        console.log(res)
                        if (res.data.code == 200) {
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 2000
                            })
                            //    更改本地评论数
                            let sale = that.data.sale;
                            sale.bbsSaleFriendsPage.commentCount = res.data.result;
                            that.setData({
                                sale: sale
                            })
                            that.getCommentList(true)
                        }
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })

    },

    /**
     * 获取评论框的输入内容
     */
    getCommentContent: function (event) {
        // console.log('获取input')

        let content = event.detail.value;
        // console.log(content);
        this.setData({
            content: content
        })
    },

    /**
     * 评论
     */
    postComment: function (e) {

        const that = this
        const content = that.data.content
        const accountState = app.globalData.accountState
        if (content == '') {
            wx.showToast({
                title: '哎呀!评论不能为空呦!',
                icon: 'none',
                duration: 2000//持续的时间
            })
        } else {
            //判断用户是否授权
            if (app.globalData.HASUSERINFO) {
                if (accountState.isDisable) {
                    wx.showToast({
                        title: `您的账号已被${accountState.stateName},剩余时间${accountState.disableDay}`,
                        icon: 'none'
                    })
                } else {
                    //    发送请求
                    var SYSUSER = wx.getStorageSync('ALLINFO').sysUser
                    const BBSRegion = wx.getStorageSync('ALLINFO').bbsRegion
                    var realname = SYSUSER.realname
                    var avatar = SYSUSER.avatar
                    console.log(that.data.beReplyRealname)
                    let bbsSaleFriendsReply = {
                        content: that.data.content,
                        topicId: that.data.objId,
                        pid: that.data.pid,
                        beReplyUsername: that.data.beReplyUsername,
                        beReplyRealname: that.data.beReplyRealname,
                        realname: realname,
                        avatar: avatar,
                        sysOrgCode: BBSRegion.sysOrgCode

                    }
                    console.log(bbsSaleFriendsReply)

                    wx.showLoading({
                        title: '发送中',
                    });
                    this.setData({
                        showCommentInput: false
                    })
                    app.wxRequest('post', app.globalData.HOSTURL + "/bbs/bbsSaleFriendsReply/wise/mini/add", bbsSaleFriendsReply).then(res => {
                        console.log(res);
                        if (res.errMsg == 'request:ok') {
                            if (res.data.code == 200) {

                                //    评论数本地加1
                                let sale = that.data.sale;
                                sale.bbsSaleFriendsPage.commentCount = sale.bbsSaleFriendsPage.commentCount + 1;
                                that.setData({
                                    sale: sale
                                })

                                //    获取评论列表

                                this.getCommentList(true);
                            } else if (res.data.code == 1000) {
                                wx.showToast({
                                    title: '未授权,无法发布。',
                                    icon: 'error',
                                    duration: 2500,
                                })
                            } else if (res.data.code == 500) {
                                wx.showToast({
                                    title: res.data.message,
                                    icon: 'error',
                                    duration: 2500//持续的时间
                                })
                            }

                            this.setData({

                                // pid:'0',
                                content: '',
                                showCommentInput: false
                            })

                        }


                    });
                }
            } else {
                app.getUserProfile()
            }


        }


    },


    /**
     * 分享
     */
    onShareAppMessage: function (res) {
        const that = this
        console.log(that.data.sale.bbsSaleFriendsPage.bbsSaleFriendsImageList[0])
        const title = "卖舍友啦，便宜又好看，五毛钱一个清仓大甩卖..."
        const path = `/pages/index/index?type=sale&id=${this.data.sale.bbsSaleFriendsPage.id}`
        const imageUrl = `${app.globalData.UPLOAD_IMAGE}${this.data.sale.bbsSaleFriendsPage.bbsSaleFriendsImageList[0].imageUrl}`
        return {
            title: title,
            path: path,
            imageUrl: imageUrl
        }
    },
})